package com.okilo.online.app.pet

import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.common.OkiloComPet
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.request.IHttpCallback
import com.okilo.online.app.pet.view.IOkiloTimeZone
import com.okilo.online.app.tools.helper.OkiloAnalysisHp
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import org.json.JSONObject
import java.util.TimeZone

/**
 * 时区相关
 */
class OkiloTimeZonePet(private val iView: IOkiloTimeZone?): OkiloComPet(iView) {

    /**
     * 获取时区转发
     * /v1/timezonePath
     */
    fun gOkiloTimeZoneRequest(){
        val httpUrl = OkiloConfigs.gOkiloTimeZoneUrl()
        val params = JSONObject().apply {
            put("p", OkiloConfigs.OKILO_APPNAME)
            put("tz", TimeZone.getDefault().id)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val timeZoneString = data.optString("data","")
                if (timeZoneString.isNotEmpty()){
                    var timeZone = ""
                    var zoneCode = ""
                    var zoneCountry = ""

                    timeZoneString.split(",").apply {
                        if (this.isNotEmpty()){
                            timeZone = this[0].trim()
                        }
                        if (this.size >= 2){
                            zoneCode = this[1].trim()
                        }
                        if (this.size >= 3){
                            zoneCountry = this[2].trim()
                        }
                    }

                    //保存转发路径
                    OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_TIMEZONE,timeZone)
                    //保存转发地区 区号
                    OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_TIMEZONE_CODE,zoneCode)
                    //保存国家标识
                    OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_TIMEZONE_COUNTRY,zoneCountry)
                    //初始化analysis lib 赋值 转发地区
                    OkiloAnalysisHp.initLibAtZoneSuccess(OkiloApplication.app)

                    iView?.sOkiloTimeZoneCallback(timeZone = timeZone)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }
}